#include "stm32f10x.h"

extern uint32_t timer_counter;

/**
 *  1. 开启时钟
 *  2. 选择时基单元的时钟源，内部时钟源。
 *  3. 时基单元配置
 *  4. 中断输出控制
 *  5. NVIC配置
 *  6. 运行控制
 *  7. 计数器使能
 *  8. 中断函数
 * **/

void Timer_init(void)
{
    // 1. 开启TIM2时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    // 2. 选择时基单元的时钟源，内部时钟源
    TIM_InternalClockConfig(TIM2);
    // 3. 时基单元配置
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitSTructure;
    // 使用内部时钟所以配置无效
    TIM_TimeBaseInitSTructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitSTructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitSTructure.TIM_Period = 10000 - 1;
    TIM_TimeBaseInitSTructure.TIM_Prescaler = 7200 - 1;
    // 高级定时器才有
    TIM_TimeBaseInitSTructure.TIM_RepetitionCounter = 0;
    // 初始化会产生中断事件
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitSTructure);
    // 清除中断标志位，防止上电进入更新中断
    TIM_ClearFlag(TIM2, TIM_FLAG_Update);
    // 4. 中断输出控制
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    // 5. NVIC
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    NVIC_InitTypeDef nvic_init_param;
    nvic_init_param.NVIC_IRQChannel = TIM2_IRQn;
    nvic_init_param.NVIC_IRQChannelCmd = ENABLE;
    nvic_init_param.NVIC_IRQChannelPreemptionPriority = 2;
    nvic_init_param.NVIC_IRQChannelSubPriority = 2;
    NVIC_Init(&nvic_init_param);

    // 6. 定时器使能
    TIM_Cmd(TIM2, ENABLE);
}

void TIM2_IRQHandler(void)
{
    // 判断标志位
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
    {
        if (timer_counter >= 99)
        {
            timer_counter = 0;
        }
        else
        {
            timer_counter++;
        }
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}
